package com.work.fn;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.function.Supplier;

public class GenerateCaptcha {
    public static void generate(Supplier<BufferedImage> supplier, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);


        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            BufferedImage bi = supplier.get();
            ImageIO.write(bi, "jpg", baos);
            byte[] imageBytes = baos.toByteArray();

            response.getOutputStream().write(imageBytes);
            response.getOutputStream().flush();
        } catch (IOException e) {
            response.sendError(500, "服务器异常");
        }
    }
}
